<?php

namespace service;

// 1.获取数据，插入数据。
// 2.数据来源file or string or 生成
// 2.1 file 使用上传的，string 用 \n分割，生成的直接是数组？预览的话？？？？存js先？就变成和前一个一样的了。
// 生成sql数据，插入，返回结果。

class WaybillUtil
{
    protected static $lists = [];
    const PHPEXCEL_PATH = VENDORPATH.'helper/excel/phpExcel/PHPExcel.php';

    /**
     * csvFileToArray
     *
     * @param  \SplFileObject $file
     * @return array
     */
    public static function csvFileToArray(\SplFileObject $file)
    {
        $array = [];
        while (!$file->eof()) {
            $array[] = $file->fgetcsv();
        }
        return $array;
    }

    /**
     * strToArray
     *
     * @param  string $str
     * @param  string|array $delimiter
     * @return array
     */
    public static function strToArray($str = '', $delimiter = ["\n",',','\s+'])
    {
        if ($str && $delimiter && is_string($str)) {
            if (is_string($delimiter)) {
                return explode($delimiter, $str);
            }elseif(is_array($delimiter)){
                //转义\\
                $delimiter = array_filter($delimiter);
                $patterns = '/'.implode('|', $delimiter).'/i';
                return preg_split($patterns, $str);
            }

        }
        return [];
    }

    /**
     * csvStrToArray
     *
     * @param  string $str
     * @param  string $delimiter
     * @return array
     */
    public static function csvStrToArray($str = '', $delimiter = ',')
    {
        $result = [];
        if (is_string($str)) {
            $str = [$str];
        }
        foreach ($str as $key => $val) {
            $result[] = str_getcsv($val, $delimiter);
        }
        return $result;
    }

    /**
     * create md serial number
     *
     * @param  integer  $start start
     * @param  integer  $end
     * @param  integer $step
     * @return array
     */
    public static function createMdNo($start = null, $end = null, $step = 1)
    {
        if ($start === null) {
            return [];
        } elseif ($end === null) {
            $end = $start + 100;
        }
        static $_lists = [];
        $_key = md5($start . $end . $step);
        return isset($_lists[$_key]) ? $_lists[$_key] : $_lists[$_key] = range($start, $end, $step);
    }

    /**
     * arrayToInsertSql
     *
     * @param  array  $data
     * @param  string $table
     * @param  boolean $operation
     * @return string
     */
    public static function arrayToInsertSql(array $data = [], $table = '', $operation = false)
    {
        if (is_array($data)) {
            //统一当作多数组处理
            if (!is_array(current($data))) {
                $data = [$data];
            }
            $fields = array_keys(current($data));
            $sql = (is_string($operation) ? strtoupper($operation) : ($operation ? 'REPLACE' : 'INSERT')) . ' INTO `'. $table .'` (`' . implode('`, `', $fields) . '` ) VALUES ';
            $values = '';
            foreach ($data as $key => $value) {
                $values .= '("' . implode('", "', $value) . '"),';
            }
            return $sql . trim($values, ',');
        }
    }

    /**
     * buildInsertData
     *
     * @param  array  $data
     * @param  array  $common_data
     * @return array
     */
    public static function buildInsertData(array $data = [], array $common_data = [])
    {
        if (!static::verifyCommonData($common_data)) {
            return false;
        }
        $insert_data = [];
        foreach ($data as $k => $val) {
            $insert_data[] = ['md_no' => $val] + $common_data;
        }
        return $insert_data;
    }

    /**
     *
     *
     * @return array
     */
    public static function buildBaseSqlData()
    {
        return [
            'express_company' => '',
            'index_shop_id' => '',
            'add_by' => '',
            // 'is_used' => 'no',
        ];
    }

    /**
     * parseExcelFile
     *
     * @param  \SplFileObject|string $file
     * @return [type]
     */
    public static function parseExcelFile($file)
    {
        if($file instanceof \SplFileObject){
            $file = $file->getRealPath();
        }
        if(!is_file($file)){
            return false;
        }
        require_once(self::PHPEXCEL_PATH);
        $reader = \PHPExcel_IOFactory::createReaderForFile($file)->setReadDataOnly(true)->load($file);
        $sheet = $reader->getActiveSheet(0);
        $highest_row = $sheet->getHighestRow();
        // $highest_column = $sheet->getHighestColumn();
        $data = [];
        for ($i = 1; $i <= $highest_row ; $i++) {
            $data[$i] = $sheet->getCell('A'.$i)->getValue();
        }
        $reader->disconnectWorksheets();
        return $data;
    }

    /**
     * verifyCommonData
     *
     * @param  array  $data
     * @return boolean
     */
    protected static function verifyCommonData(array $data)
    {
        $common_data = [
                'express_company' => '',
                'index_shop_id' => '',
                'add_by' => '',
            ];
        return count(array_intersect_key($data, $common_data)) === count($common_data);
    }

    /**
     * getCsvStringDelimiter
     *
     * @param  string $str
     * @return string|null
     */
    protected static function getCsvStringDelimiter($str = null)
    {
        if (is_string($str) && $str) {
            $str = strstr($str, "\n", true) ?: $str;
            $t = "\t";
            $s = ',';
            return substr_count($str, $t) > substr_count($str, $s) ? $t : $s;
        }
    }
}
